package com.bestvike.stone.spring.page;

import com.alibaba.fastjson.annotation.JSONField;
import com.github.pagehelper.Page;
import lombok.Data;
import org.springframework.util.Assert;

import java.util.List;

/**
 * 分页响应
 */
@Data
public class PageableResponse<T> {
    @JSONField(ordinal = 1)
    private long totalCount;//总行数
    @JSONField(ordinal = 2)
    private int pageCount;//总页数
    @JSONField(ordinal = 3)
    private int displayCount;//当前页数据行数
    @JSONField(ordinal = 4)
    private List<T> list;//数据

    /**
     * 创建一个分页响应
     *
     * @param page 分页信息, 必须为 Page 类型
     * @param <T>  元素类型
     * @return 分页响应
     */
    public static <T> PageableResponse<T> create(List<T> page) {
        Assert.notNull(page, "list can not be null");
        if (!(page instanceof Page))
            throw new RuntimeException("page type error");

        Page<T> pageData = (Page<T>) page;
        PageableResponse<T> pageableResponse = new PageableResponse<>();
        pageableResponse.setTotalCount(pageData.getTotal());
        pageableResponse.setPageCount(pageData.getPages());
        pageableResponse.setDisplayCount(pageData.size());
        pageableResponse.setList(pageData);
        return pageableResponse;
    }

    /**
     * 创建一个分页响应
     *
     * @param page 分页信息, 必须为 Page 类型
     * @param list 要返回的数据
     * @param <T>  元素类型
     * @return 分页响应
     */
    public static <T> PageableResponse<T> create(List<?> page, List<T> list) {
        Assert.notNull(page, "page can not be null");
        Assert.notNull(list, "list can not be null");
        if (!(page instanceof Page))
            throw new RuntimeException("page type error");

        Page<?> pageData = (Page<?>) page;
        PageableResponse<T> pageableResponse = new PageableResponse<>();
        pageableResponse.setTotalCount(pageData.getTotal());
        pageableResponse.setPageCount(pageData.getPages());
        pageableResponse.setDisplayCount(list.size());
        pageableResponse.setList(list);
        return pageableResponse;
    }
}
